package com.yaolaizaixian.merchant.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yaolaizaixian.merchant.R;
import com.yaolaizaixian.merchant.base.BaseActivity;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.bean.CreadOrderModel;
import com.yaolaizaixian.merchant.bean.CustomerInfo;
import com.yaolaizaixian.merchant.bean.OrderLsfp;
import com.yaolaizaixian.merchant.bean.OrderLsm;
import com.yaolaizaixian.merchant.utils.AppManager;
import com.yaolaizaixian.merchant.utils.GsonUtil;
import com.yaolaizaixian.merchant.utils.LogUtil;
import com.yaolaizaixian.merchant.utils.MyNetUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.yaolaizaixian.merchant.utils.Toasty;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/4/26.
 * <p/>
 * 确认收款页面
 */
public class ConfirmActivity extends BaseActivity {

    @BindView(R.id.ll_back)
    AutoLinearLayout llBack;
    @BindView(R.id.tv_title_text)
    TextView tvTitleText;
    @BindView(R.id.tv_confirm_name)
    TextView tvConfirmName;
    @BindView(R.id.dashLine)
    LinearLayout dashLine;
    @BindView(R.id.tv_confirm_rank)
    TextView tvConfirmRank;
    @BindView(R.id.tv_confirm_time)
    TextView tvConfirmTime;
    @BindView(R.id.dashLine1)
    LinearLayout dashLine1;
    @BindView(R.id.tv_confirm_totalmoney)
    TextView tvConfirmTotalmoney;
    @BindView(R.id.dashLine2)
    LinearLayout dashLine2;
    @BindView(R.id.tv_confirm_youhui)
    TextView tvConfirmYouhui;
    @BindView(R.id.tv_confirm_coinjin)
    TextView tvConfirmCoinjin;
    @BindView(R.id.tv_confirm_paytype)
    TextView tvConfirmPaytype;
    @BindView(R.id.dashLine3)
    LinearLayout dashLine3;
    @BindView(R.id.tv_confirm_momey)
    TextView tvConfirmMomey;
    @BindView(R.id.rl_order_erweima)
    AutoRelativeLayout rlOrderErweima;
    private String TAG = "ConfirmActivity";
    //标记是否是点击了订单确定按钮 1 没点 2 点击
    private String sign="";
    private OrderLsfp orderLsfp;

    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:

                    String result = (String) msg.obj;
                    LogUtil.LogShitou(TAG, result);
                    BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);
                    if (baseModel.isFlag()) {

                        CreadOrderModel creadOrderModel = GsonUtil.jsonToBean(result, CreadOrderModel.class);
                        OrderLsm orderLsm = creadOrderModel.getData().getLsm();
                        CustomerInfo customerInfo = creadOrderModel.getData().getCustomer();
                         orderLsfp= creadOrderModel.getData().getLsfp();
                        //订单id
                        String sysno = orderLsm.getSysno();

                        if (!TextUtils.isEmpty(customerInfo.getCustomername())&!TextUtils.isEmpty(customerInfo.getCustomerid())){

                            tvConfirmName.setText(customerInfo.getCustomername().substring(0,1)+"先生/女士("+customerInfo.getCustomerid().substring(0,3)+"****"+customerInfo.getCustomerid().substring(7)+")");
                        }
                        else if (!TextUtils.isEmpty(customerInfo.getCustomername())&TextUtils.isEmpty(customerInfo.getCustomerid())){

                            tvConfirmName.setText(customerInfo.getCustomername().substring(0,1)+"先生/女士");
                        }
                        else if (TextUtils.isEmpty(customerInfo.getCustomername())&!TextUtils.isEmpty(customerInfo.getCustomerid())){

                            tvConfirmName.setText(customerInfo.getCustomerid().substring(0,3)+"****"+customerInfo.getCustomerid().substring(7));
                        }

                        tvConfirmTime.setText(orderLsm.getInputTime());
                        tvConfirmTotalmoney.setText("￥"+orderLsfp.getTotalAmt());
                        tvConfirmYouhui.setText("-￥"+orderLsfp.getDerateAmt());
                        tvConfirmCoinjin.setText("-￥"+orderLsfp.getCoinAmt());

                        if ("168".equals(orderLsfp.getPayTypeSysno())){

                            tvConfirmPaytype.setText("微信支付");
                        }
                        //之前的订单，全部归结为线下
                        else
                        {
                            tvConfirmPaytype.setText("线下支付");
                        }

                        //会员等级判断
                        if (customerInfo.getCustomerrank()== 100) {

                            tvConfirmRank.setText("普通会员");

                        } else if (customerInfo.getCustomerrank() == 200) {

                            tvConfirmRank.setText("白金尊荣会员");


                        }  else if (customerInfo.getCustomerrank() == 300) {

                            tvConfirmRank.setText("尊荣会员");


                        }  else if (customerInfo.getCustomerrank() == 400) {

                            tvConfirmRank.setText("钻石会员");

                        }
                        else if (customerInfo.getCustomerrank() == 500) {

                            tvConfirmRank.setText("黑金会员");
                        }
                       tvConfirmMomey.setText("￥"+orderLsfp.getPayPrice());

                        //点击按钮时跳转
                        if (sign.equals("2")){

                            //订单状态
//                        订单状态 5：待确定，10：待付款，15已付款，-100：取消
                            if ("-100".equals(orderLsm.getStatus())){
                                //跳到取消
                                Intent intent = new Intent(ConfirmActivity.this, CancelOrderActivity.class);
                                intent.putExtra("sysno", sysno);
                                startActivity(intent);

                            }
                            else if("10".equals(orderLsm.getStatus()))
                            {


                                setData();
                            }
                            else if (Integer.parseInt(orderLsm.getStatus()) >= 15){

                                //已付款待补录
                                  if ("0".equals(creadOrderModel.getData().getIsDitional())){
                                    //跳到补录
                                    Intent intent = new Intent(ConfirmActivity.this, OrderSuccessActivity.class);
                                    intent.putExtra("sysno", sysno);
                                    startActivity(intent);
                                }
                            }

                            SharedPreferencesUtil.saveBoolean(getApplicationContext(), "signRefresh", true);

                        }

                    } else {

                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode)) {
                            showConflictDialog(ConfirmActivity.this, "账号被停用");

                        } else if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode1)) {

                            showConflictDialog(ConfirmActivity.this, "您的账号在其它设备登录");

                        } else {
                            Toast.makeText(ConfirmActivity.this, baseModel.getErrorMsg(), Toast.LENGTH_SHORT);
                            return;
                        }
                    }

                    break;

                case 2:

                    String result2 = (String) msg.obj;
                    LogUtil.LogShitou(TAG, "=============="+result2);
                    BaseModel baseModel2 = GsonUtil.jsonToBean(result2, BaseModel.class);
                    if (baseModel2.isFlag()) {

                    //已付款 补录页面
                    Intent intent = new Intent(ConfirmActivity.this, OrderSuccessActivity.class);
                    intent.putExtra("sysno", sysno);
                    startActivity(intent);

                    }
                    else {

                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel2.getErrorCode().equals(BaseInfo.LogOutCode)) {
                            showConflictDialog(ConfirmActivity.this, "账号被停用");

                        } else if (baseModel2.getErrorCode().equals(BaseInfo.LogOutCode1)) {

                            showConflictDialog(ConfirmActivity.this, "您的账号在其它设备登录");

                        } else {
                            Toast.makeText(ConfirmActivity.this, baseModel2.getErrorMsg(), Toast.LENGTH_SHORT);
                            return;
                        }

                    }
                    break;

            }
        }
    };
    private String sysno;


    @Override
    public void initView() {

        setContentView(R.layout.activity_confirm);
    }
private String userid;
    @Override
    public void initData() {

        sysno = getIntent().getStringExtra("sysno");
        tvTitleText.setText("订单详情");

        //用户id
        userid = SharedPreferencesUtil.getString(getApplicationContext(), "usersysno", "");
        sign="1";

        SharedPreferencesUtil.saveBoolean(getApplicationContext(), "signRefresh", true);

        getData(sysno);
    }

    //订单详情
    private void getData(String sysno) {

        try {

            HashMap<String, String> sortedParams = new HashMap<String, String>();

            final String url = BaseInfo.URL + "lifeOrderController/lifeOrderInfo.do";
            // sysNo 值  3des加密
            //订单id
            sortedParams.put("lifeOrderSysno", sysno);
            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, this))
                    .build()
                    .execute(new MyStringCallback());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //线下订单收款
    private void setData() {

        try {

            HashMap<String, String> sortedParams = new HashMap<String, String>();

//            lifePaySysno	是	string	支付主键Id
//            lifeSysno	是	string	订单id
//            userId	是	string	店员Id
            final String url = BaseInfo.URL + "lifeOrderController/confirmReceiveMoney.do";
            // sysNo 值  3des加密
            //支付主键Id
            sortedParams.put("lifePaySysno", orderLsfp.getSysno());
            //订单id
            sortedParams.put("lifeSysno", sysno);
            //店员Id
            sortedParams.put("userId", userid);
            Log.e(TAG, "lifePaySysno" + orderLsfp.getSysno());
            Log.e(TAG, "lifeSysno" + sysno);
            Log.e(TAG,"userId"+userid);
            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, this))
                    .build()
                    .execute(new MyStringCallback2());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }






    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);

        AppManager.getAppManager().addActivity(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        AppManager.getAppManager().finishActivity(this);
    }

    @OnClick({R.id.ll_back, R.id.rl_order_erweima})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_back:

                finish();

                break;


            case R.id.rl_order_erweima:

                //点击后跳
                sign="2";
                getData(sysno);

                break;
        }
    }

    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {

            Toasty.error(ConfirmActivity.this, "请检查网络", Toast.LENGTH_SHORT, true).show();
            Log.e(TAG, e.toString());

        }

        @Override
        public void onResponse(String response, int id) {

            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mhandler.sendMessage(message);
        }
    }
    class MyStringCallback2 extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {

            Toasty.error(ConfirmActivity.this, "请检查网络", Toast.LENGTH_SHORT, true).show();
            Log.e(TAG, e.toString());

        }

        @Override
        public void onResponse(String response, int id) {

            Message message = new Message();
            message.what = 2;
            message.obj = response;
            mhandler.sendMessage(message);
        }
    }
}
